package edu.cqie.smartfarm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.cqie.smartfarm.entity.City;
import edu.cqie.smartfarm.mapper.CityMapper;
import edu.cqie.smartfarm.service.ICityService;
import edu.cqie.smartfarm.vo.CityVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 基础表-省市区 服务实现类
 * </p>
 *
 * @author yyw
 * @since 2024-12-29
 */
@Service
@RequiredArgsConstructor
public class CityServiceImpl extends ServiceImpl<CityMapper, City> implements ICityService {
    private final CityMapper cityMapper;

    /**
     * 获取所有城市
     * @return
     */
    @Override
    public List<CityVO> getAll() {
        /*// 现将省份数据查询出来
        LambdaQueryWrapper<City> queryWrapper = new LambdaQueryWrapper<City>()
                .eq(City::getLevel, 1)
                .orderByAsc(City::getSort);
        List<City> provinceList = cityMapper.selectList(queryWrapper);
        List<CityVO> propertiesVOList = BeanUtil.copyToList(provinceList, CityVO.class);

        // 获取所有市
        LambdaQueryWrapper<City> cityQueryWrapper = new LambdaQueryWrapper<City>()
                .eq(City::getLevel, 2)
                .orderByAsc(City::getSort);
        List<City> cityList = cityMapper.selectList(cityQueryWrapper);
        List<CityVO> cityVOList = BeanUtil.copyToList(cityList, CityVO.class);



        // 遍历省份数据，将每个省份的子级查询出来
        cityVOList.forEach(cityVO -> {
            LambdaQueryWrapper<City> cityQueryWrapper1 = new LambdaQueryWrapper<City>()
                    .eq(City::getParentId, cityVO.getId())
                    .eq(City::getLevel, 3)
                    .orderByAsc(City::getSort);
            List<City> areasList = cityMapper.selectList(cityQueryWrapper1);
            cityVO.setChildren(BeanUtil.copyToList(areasList, CityVO.class));
        });

        // 匹配省份id和城市父级id
        propertiesVOList.forEach(propertiesVO -> {
            // 将每个父级id一样的市数据放入到对应的省份中
            propertiesVO.setChildren(new ArrayList<>());
            cityVOList.forEach(cityVO -> {
                if (Objects.equals(cityVO.getParentId(), propertiesVO.getId())) { // 匹配省份id和城市父级id
                    propertiesVO.getChildren().add(cityVO);
                }
            });
        });

        return propertiesVOList;*/
        try {
            // 合并查询，一次性获取所有级别为1、2、3的城市，并按parentId分组
            LambdaQueryWrapper<City> queryWrapper = new LambdaQueryWrapper<City>()
                    .in(City::getLevel, Arrays.asList(1, 2, 3))
                    .orderByAsc(City::getSort);
            List<City> allCities = cityMapper.selectList(queryWrapper);

            // 将所有城市转换为 CityVO 对象
            Map<Integer, List<City>> groupedByParentId = allCities.stream()
                    .collect(Collectors.groupingBy(City::getParentId));

            List<CityVO> propertiesVOList = BeanUtil.copyToList(
                    groupedByParentId.getOrDefault(0, Collections.emptyList()), // 省份 parentId 通常为 0 或 null
                    CityVO.class
            );

            // 构建树形结构
            for (CityVO province : propertiesVOList) {
                List<CityVO> children = groupedByParentId.getOrDefault(province.getId(), Collections.emptyList())
                        .stream()
                        .map(city -> BeanUtil.copyProperties(city, CityVO.class))
                        .collect(Collectors.toList());

                province.setChildren(children);

                // 设置区县作为城市的子节点
                for (CityVO city : children) {
                    city.setChildren(groupedByParentId.getOrDefault(city.getId(), Collections.emptyList())
                            .stream()
                            .map(area -> BeanUtil.copyProperties(area, CityVO.class))
                            .collect(Collectors.toList()));
                }
            }

            return propertiesVOList;
        } catch (Exception e) {
            // 异常处理逻辑
            throw new RuntimeException("获取城市列表时出错", e);
        }
    }
}
